package com.dsprun.dspai.config;

//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.web.SecurityFilterChain;
//
//@Configuration
//@EnableWebSecurity
//public class SecurityConfig {
//    @Bean
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        http
//                .csrf(csrf -> csrf.disable()) // 禁用CSRF
//                .authorizeHttpRequests(auth -> auth
//                        .requestMatchers("/api/ai/**").permitAll() // 允许匿名访问AI接口
//                        .anyRequest().authenticated()
//                );
//        return http.build();
//    }
//}

//
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.util.Arrays;
import java.util.List;

/**
 * Spring Security 核心配置类
 * 功能涵盖：
 * 1. 路由权限控制
 * 2. CSRF防护配置
 * 3. CORS跨域支持
 * 4. 会话管理
 * 5. 开发/生产环境差异化配置
 * 6. JWT认证集成点
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 启用方法级安全注解（如@PreAuthorize）
public class SecurityConfig {

    private final Environment env;

    // 无需认证的公共端点（可按需扩展）
    private static final String[] PUBLIC_ENDPOINTS = {
            "/api/public/**",
            "/auth/login",
            "/api/ai/**",
            "/auth/register",
            "/swagger-ui/**",
            "/swagger-ui.html",
            "/v3/api-docs/**",
            "/error"
    };

    public SecurityConfig(Environment env) {
        this.env = env;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 环境检查：如果是开发环境，放宽安全限制
        boolean isDevEnv = Arrays.asList(env.getActiveProfiles()).contains("dev");

        http
                // 1. 禁用CSRF（根据环境动态配置）
                .csrf(csrf -> {
//                    if (isDevEnv) {
//                        csrf.disable(); // 开发环境禁用CSRF
//                    } else {
                        // 生产环境配置CSRF（需要前端配合传递X-CSRF-TOKEN）
                        csrf.ignoringRequestMatchers(PUBLIC_ENDPOINTS)
                                .csrfTokenRepository(new CookieCsrfTokenRepository());
//                    }
                })

                // 2. CORS配置（跨域资源共享）
//                .cors(cors -> cors.configurationSource(corsConfigurationSource()))

                // 3. 会话管理：无状态（适合REST API）
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )

                // 4. 请求授权配置
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(PUBLIC_ENDPOINTS).permitAll() // 公共端点
                        .requestMatchers("/api/admin/**").hasRole("ADMIN") // 管理员端点
                        .requestMatchers("/api/user/**").hasAnyRole("USER", "ADMIN") // 用户端点
                        .anyRequest().authenticated() // 其他所有端点需要认证
                )

                // 5. JWT过滤器（示例配置，需替换为实际实现）
//                .addFilterBefore(
//                        new JwtAuthenticationFilter(),
//                        UsernamePasswordAuthenticationFilter.class
//                )

                // 6. 异常处理
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(new Http401AuthenticationEntryPoint()) // 未认证处理
                        .accessDeniedHandler(new Http403AccessDeniedHandler()) // 权限不足处理
                );

        return http.build();
    }
//
//    /**
//     * CORS全局配置（可根据需求调整）
//     */
//    @Bean
//    CorsConfigurationSource corsConfigurationSource() {
//        CorsConfiguration config = new CorsConfiguration();
//
//        // 允许的源（生产环境应替换为具体域名）
//        config.setAllowedOrigins(List.of("*"));
//
//        // 允许的HTTP方法
//        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
//
//        // 允许的请求头
//        config.setAllowedHeaders(List.of("*"));
//
//        // 是否允许凭证（如Cookies）
//        config.setAllowCredentials(false);
//
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", config);
//        return source;
//    }
//
//    // 示例：JWT过滤器（需自行实现）
//    private static class JwtAuthenticationFilter extends OncePerRequestFilter {
//        @Override
//        protected void doFilterInternal(HttpServletRequest request,
//                                        HttpServletResponse response,
//                                        FilterChain filterChain) {
//            // 实现JWT解析和认证逻辑
//        }
//    }
//
    // 示例：401未认证响应处理器
    private static class Http401AuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request,
                             HttpServletResponse response,
                             AuthenticationException authException) {
            response.setContentType("application/json");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            // 返回JSON格式错误信息
        }
    }
//
    // 示例：403权限不足响应处理器
    private static class Http403AccessDeniedHandler implements AccessDeniedHandler {
        @Override
        public void handle(HttpServletRequest request,
                           HttpServletResponse response,
                           AccessDeniedException accessDeniedException) {
            response.setContentType("application/json");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            // 返回JSON格式错误信息
        }
    }
}